﻿using System.Text.RegularExpressions;
using System.Web;

namespace CodeContrib.Web
{
	public static class SeoExtensions
	{
		public static void VerifySeoUrl(this HttpContext httpContext)
		{
			if (httpContext.Request.HttpMethod.ToUpper() != "GET")
			{
				return;
			}

			var doRedirect = false;

			var url = string.Format("{0}://{1}{2}", httpContext.Request.Url.Scheme, httpContext.Request.Url.Authority, httpContext.Request.Url.AbsolutePath);

			if (httpContext.Request.Url.AbsolutePath != "/"
			    && httpContext.Request.Url.AbsolutePath.EndsWith("/"))
			{
				url = url.Substring(0, url.Length - 1);

				doRedirect = true;
			}

			if (httpContext.Request.Url.AbsolutePath.Contains("//"))
			{
				url = url.Replace("//", "/");

				doRedirect = true;
			}

			if (Regex.IsMatch(url, @"[A-Z]"))
			{
				url = url.ToLower();

				doRedirect = true;
			}

			url += httpContext.Request.Url.Query;

			if (doRedirect)
			{
				httpContext.Response.Clear();
				httpContext.Response.Status = "301 Moved Permanently";
				httpContext.Response.AddHeader("Location", url);
				httpContext.Response.End();
			}
		}
	}
}